Ext.Loader.setConfig({enabled: true});

//Ext.Loader.setPath('Ext.ux', './ux');
Ext.Loader.setPath('Ext.ux', '/pemilukada/ux');

Ext.require([
    'Ext.tip.QuickTipManager',
    'Ext.container.Viewport',
    'Ext.layout.*',
    'Ext.form.Panel',
    'Ext.form.Label',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.tree.*',
    'Ext.selection.*',
    'Ext.tab.Panel',
    'Ext.ux.GMapPanel'
]);



//ditaroh diluar biar bisa dipanggil di console
var myGMapPanel;
var detailsPanel; //di West --> South
var treePanel; //treePanel di West -> North
var contentPanel;
var chart;//chart
var FM_map; //google map
var current_record;
//
// This is the main layout definition.
//
Ext.onReady(function(){






//###===== START CHART


    var browserStore = Ext.create('Ext.data.JsonStore', {
        fields: fields,
        data: jsonData //ada di file chart.js
    });



    var colors = ['rgb(47, 162, 223)',
                  'rgb(60, 133, 46)',
                  'rgb(234, 102, 17)',
                  'rgb(154, 176, 213)',
                  'rgb(186, 10, 25)',
                  'rgb(40, 40, 40)'];

    Ext.chart.theme.Browser = Ext.extend(Ext.chart.theme.Base, {
        constructor: function(config) {
            Ext.chart.theme.Base.prototype.constructor.call(this, Ext.apply({
                colors: colors
            }, config));
        }
    });

    chart = Ext.create('Ext.chart.Chart', {
		title:'Grafik untuk Kelurahan',
		id: 'chartCmp',
		xtype: 'chart',
		style: 'background:#fff',
		animate: true,
		theme: 'Browser:gradients',
		defaultInsets: 30,
		store: browserStore,
		
		legend: {
			position: 'right'
		},
		
		axes: [{
			type: 'Numeric',
			position: 'left',
			fields: fields.slice(1),
			title: 'Pemilih %',
			grid: true,
			decimals: 0,
			minimum: 0,
			maximum: 100
		}, {
			type: 'Category',
			position: 'bottom',
			fields: ['date'],
			title: 'TPS',
			label: {
				renderer: function(v) {
					return v.match(/([0-9]*)\/[0-9]*\/[0-9][0-9]([0-9]*)/).slice(1).join('/');
				}
			}
		}],
		
		series: [{
			type: 'area',
			axis: 'left',
			highlight: true,
			tips: {
			  trackMouse: true,
			  width: 170,
			  height: 28,
			  renderer: function(storeItem, item) {
				  this.setTitle(item.storeField + ' - '
						  + Ext.Date.format(new Date(storeItem.get('date')), 'M y')
						  + ' - ' + storeItem.get(item.storeField) + '%');
			  }
			},
			xField: 'name',
			yField: fields.slice(1),
			style: {
				lineWidth: 1,
				stroke: '#666',
				opacity: 0.86
			}
		}]
	});
 

//###==== END CHART














    Ext.tip.QuickTipManager.init();

    // This is an inner body element within the Details panel created to provide a "slide in" effect
    // on the panel body without affecting the body's box itself.  This element is created on
    // initial use and cached in this var for subsequent access.
    var detailEl;
    //sepertinya ini menyebabkan error pada gmap kita kah?

    // Gets all kelurahan
    var kelurahan = [];

    Ext.Object.each(getBasicLayouts(), function(name, example) {
        kelurahan.push(example);
    });


    //contentPanel adalah panel yang ada ditengah
    // This is the main content center region that will contain each example layout panel.
    // It will be implemented as a CardLayout since it will contain multiple panels with
    // only one being visible at any given time.
    contentPanel = {
        title:'Home', //saya tambahkan title di sini agar yang lebih penting itu datanya, bukan petanya
         id: 'content-panel',
         region: 'center', // this is what makes this panel into a region within the containing layout
         layout: 'card',
         margins: '2 5 5 0',
         activeItem: 0,
         border: false,
         items: kelurahan
    };

    //dikiri ada dua, treePanel di atas dan detailsPanel di bawah
    // The TreePanel provides tree-structured UI representation of tree-structured data. A TreePanel must be bound to a Ext.data.TreeStore. TreePanel's support multiple columns through the columns configuration.

    //data untuk tree di kiri
    var store = Ext.create('Ext.data.TreeStore', {
        root: {
            expanded: true
        },
        proxy: {
            type: 'ajax',
            //url proxy yang akan memberikan data kecamatan dan kelurahan dari database kita,
            //dihandle oleh CodeIgniter controller JSON, fungsi tree
            url: '/json/tree'
        }
    });

    // Go ahead and create the TreePanel now so that we can use it below.
     treePanel = Ext.create('Ext.tree.Panel', {
        id: 'tree-panel',
        title: 'Geografi',
        region:'north',
        split: true,
        height: 260,
        minSize: 150,

        //rootVisible : Boolean
        //False to hide the root node.
        //Defaults to: true
        rootVisible: false,

        //autoScroll : Boolean
        //true to use overflow:'auto' on the components layout element and show scroll bars automatically when necessary, false to clip any overflowing content. This should not be combined with overflowX or overflowY.
        //Defaults to: false
        autoScroll: true,

        //Required Config options
        //store : Ext.data.TreeStore    REQUIRED
        //The Store the tree should use as its data source.
        store: store,

        dockedItems: [{
            xtype: 'toolbar',
            items: {
                text: 'Update Peta',
                handler: function(){
                    var records = treePanel.getView().getChecked();
                    //getView( ) : Ext.view.Table
                    //Gets the view for this panel.
                    //Returns
                    //Ext.view.Table

                    //getChecked( ) : Ext.data.NodeInterface[]
                    //Retrieve an array of checked records.
                    //Returns
                    //Ext.data.NodeInterface[]
                    //An array containing the checked records

                    var names = [];//empty array untuk meyimpan text

                    Ext.Array.each(records, function(rec){
                        names.push(rec.get('text'));
                    });

                    Ext.MessageBox.show({
                        title: 'Check Box yang dipilih',
                        msg: names.join('<br />'),
                        icon: Ext.MessageBox.INFO
                    });
                }
            }
        }]


    });

    // Assign the changeLayout function to be called on tree node click.
    treePanel.getSelectionModel().on('select', function(selModel, record) {
		current_record=record;
        if (record.get('leaf')) {
            console.log('Event: select on record : ' + record.getId());
            console.log('Event: select on ' + record.get('text'));
			
			//update chart
			Ext.getCmp('chartCmp').title= record.get('text');
			chart.axes.items[1].title = 'TPS di '+record.get('text');
			chart.redraw();
			
			//update map
			path2polygon(record.getId());//ini hasilnya malah DOMnya
			//path2polygon(record.internalID.toString());//yang ini dikonsol ada, tapi di script kaga

            //Ext.getCmp('content-panel').layout.setActiveItem(record.getId() + '-panel');
            Ext.getCmp('content-panel').layout.setActiveItem(record.getId());
            if (!detailEl) {
                //update details-panel
                //var bd = Ext.getCmp('details-panel').body;
                //bd.update('').setStyle('background','#fff');
                //detailEl = bd.createChild(); //create default empty div
            }

            //hide old detail, then update with a new one which is from HTML id
            //detailEl.hide().update(Ext.getDom(record.getId() + '-details').innerHTML).slideIn('l', {stopAnimation:true,duration: 200});

        }
    });

    // This is the Details panel
    detailsPanel = {
        id: 'details-panel',
        title: 'News Update',
        region: 'center',
        bodyStyle: 'padding-bottom:15px;background:#eee;',
        autoScroll: true,

        //default HTML jika treePanel leaf belum di klik
        html: '<p class="details-info">Disini nantinya akan berisi update terbaru secara realtime dari server.</p>'
    };


	
    // Finally, build the main layout once all the pieces are ready.  This is also a good
    // example of putting together a full-screen BorderLayout within a Viewport.
    Ext.create('Ext.Viewport', {
        layout: 'border',
        title: 'Ext Layout Browser',
        items: [{
            xtype: 'box',
            id: 'header',
            region: 'north',
            html: '<h1> Sistem Informasi Pemilukada Kota Pekanbaru - Febri Mahendra</h1>',
            height: 30
        },{
            //awalnya border, sepertinya lebih baik kalau menggunakan accordion
            layout: 'border',
            id: 'layout-browser',
            region:'west',
            border: false,
            split:true,
            collapsible: true,  //update: collapsible
            margins: '2 0 5 5',
            width: 275,
            minSize: 100,
            maxSize: 500,
            items: [treePanel, detailsPanel]
        },{
            xtype: 'tabpanel',
            layout:'fit',
            region:'center',
			deferredRender: false, // set this so we have access to the map on the second tab before its been activated
            activeTab: 0, // index or id
            items:[
				//tab pertama kita adalah contentPanel
                contentPanel, //lihat penjelasan contentPanel di atas
				//myGMapPanel,
				

			
				{
                    title: 'Grafik',
					id:'tab-grafik',
                    layout: 'fit',
                    //html: 'Ini rencananya akan diisi dengan statistik.'
                    tbar: [{
                        text: 'Save Chart',
                        handler: function() {
                            Ext.MessageBox.confirm('Confirm Download', 'Ingin download Grafik ini sebagai Gambar PNG?', function(choice){
                                if(choice == 'yes'){
                                    chart.save({
                                        type: 'image/png'
                                    });
                                }
                            });
                        }
                    }],
                    items: chart
                    

                },{
                    title: 'Peta',
                    layout: 'fit',
                    tbar: [{ //top bar toolbar
                        text: 'Load Peta',
                        handler: function() {
                            //
							window['mapOptions'] = {
							  center: kel_tangkerang_selatan,
							  zoom: 14,
							  mapTypeId: google.maps.MapTypeId.ROADMAP
							};
							window['FM_map'] = new google.maps.Map(document.getElementById("peta"),mapOptions);
							
                        }
                    }],					
					html: '<div id="peta" style="width:100%;height:100%">Ini rencananya akan diisi dengan configurasi, misalnya: login, dsb.</div>'
				   //contentEl:'map_canvas'
                }

				
            ]
        }
        ],
        renderTo: Ext.getBody()
    });
	
	//force myGMapPanel to create map
	//if(console)console.log('forcing myGMapPanel to createMap');
	//Ext.getCmp('my-gmap-panel').createMap(myGMapPanel.center,myGMapPanel.markers);

});

